import React, { useCallback, useEffect, useState } from 'react'
import Taro from '@tarojs/taro'
import { View, Image, Text
} from '@tarojs/components'
import LoginVerifyBtn from '@COMPONENTS/Button/LoginVerifyBtn'
import DBConfig from '@CONFIG/DBConfig'
import Images from '@ASSET/Images'
import { openPage } from '@UTILS/common'
import { Analytic_Type } from '@CONSTANTS/analytic'
import { EventsITF } from '@INTERFACES/Events'
import api from '@API'
import style from './ExpertBanner.module.scss'

interface Props {
  showLogin: () => void
}

const ExpertBanner: React.FC<Props> = ({ showLogin }) => {
  const language = 'zh'
  const [data, setData] = useState<EventsITF[]>([])

  const onClickItem = useCallback(
    (RouteType, RouteData) => {
      openPage(RouteType, RouteData)
      Taro.tracker.trackEvent(Analytic_Type.tap_expert_banner.eventId, { RouteType })
    },
    []
  )

  useEffect(() => {
    api.getEventsListBySpotCode({ code: 'TengaiTabSpot' }).then(result => {
      setData(result)
    }).catch(error => {
      Taro.showToast({
        title: error?.message || error,
        icon: 'none',
      })
    })
  }, [])

  if (data.length === 0) return null

  return (
    <View className={style.container}>
      {data.map((v, i) => {
        const {
          BannerFileName, RouteType, RouteData, Title, RequestLogin
        } = v || {}

        const title = Title[language].slice(0, 5)
        const src = BannerFileName?.[language]
          ? `${DBConfig.staticBannerImageUrl}${BannerFileName?.[language]}`
          : Images.avatar

        return (
          <LoginVerifyBtn
            key={i}
            showLogin={showLogin}
            disabledVerify={!RequestLogin}
            onClick={() => onClickItem(RouteType, RouteData)}
            loginSuccess={() => onClickItem(RouteType, RouteData)}
          >
            <View className={style.item}>
              <Image src={src} className={style.image} mode="scaleToFill" />
              <Text>{title}</Text>
            </View>
          </LoginVerifyBtn>
        )
      })}
    </View>
  )
}

export default React.memo(ExpertBanner)

